<script lang="ts" setup>
import {onMounted, ref} from 'vue'
import {useForm} from '@inertiajs/vue3'
import {FormInstance, Message} from '@arco-design/web-vue'
import {route} from "ziggy-js"
import AuthLayout from "./Layout.vue";
import useRequest from "@/composables/useRequest.ts";


const {post} = useRequest()
const captchaSrc = ref(`/captcha/math?t=${Math.random()}`)
const countdown = ref(0)
// 注册状态
const isLoading = ref(false)
const isSending = ref(false)
// 表单实例
const FormRef = ref<FormInstance>(null);
const form = useForm({
    phone: '18715006008',
    sms_code: '',
    password: '',
    confirm_password: '',
    captcha: '',
    key: '',
    agreeToTerms: false
})
// 表单验证规则
const rules = {
    phone: [
        { required: true, message: '请输入手机号', trigger: 'blur' },
        { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号格式', trigger: 'blur' }
    ],
    sms_code: [
        { required: true, message: '请输入短信验证码', trigger: 'blur' },
        { len: 6, message: '验证码应为6位数字', trigger: 'blur' }
    ],
    password: [
        { required: true, message: '请输入密码', trigger: 'blur' },
        { min: 6, message: '密码长度不能少于6位', trigger: 'blur' }
    ],
    confirm_password: [
        { required: true, message: '请输入确认密码', trigger: 'blur' },
        {
            validator: (value: string, callback: any) => {
                if (value !== form.password) {
                    callback('两次输入密码不一致')
                }
            },
            trigger: 'blur'
        }
    ],
    captcha: [
        { required: true, message: '请输入验证码', trigger: 'blur' }
    ],
    agreeToTerms: [
        {
            validator: (value: boolean, callback: any) => {
                if (!value) {
                    callback('请阅读并同意用户协议')
                }
            },
            trigger: 'change'
        }
    ]
}

// 刷新验证码
const refreshCaptcha = () => {
    captchaSrc.value = `/captcha/math?t=${Math.random()}`;
};

// 倒计时定时器
const timer = ref()

const startCountdown = () => {
    setTimeout(() => {
        isSending.value = false
        countdown.value = 60
        Message.success('验证码已发送')

        // 开始倒计时
       timer.value = setInterval(() => {
            countdown.value--
            if (countdown.value <= 0) {
                clearInterval(timer.value)
            }
        }, 1000)
    }, 1000)
}

const sendSmsCode = async () => {
    // 先验证手机号和图形验证码
    if (isSending.value ) {
        return
    }
    try {
        await FormRef.value?.validateField('phone')
        const res = await post(route('auth.sms'), {
            phone: form.phone,
        })
        form.key = res.data.key
        form.sms_code = res.data.code
        isSending.value = true
        startCountdown()
    } catch (error:any) {
        Message.error(error?.message ?? '短信验证码发送失败')
        clearInterval(timer.value)
        return
    }finally {
        isSending.value = false
    }
}

const submitRegister = async () => {
    // 验证表单
    try {
        await FormRef.value?.validate();
    } catch (error) {
        return;
    }

    isLoading.value = true
    form.post(route('register.authenticate'), {
        onSuccess: () => {
            Message.success('注册成功')
        },
        onError: (errors) => {
            Message.error('注册失败，请检查您填写的信息');
            refreshCaptcha();
            const fields = {} as any;
            // 遍历所有错误
            for (const [fieldName, messages] of Object.entries(errors)) {
                // 构造字段对象
                fields[fieldName] = {
                    status: 'error',
                    message: messages
                };
            }
            FormRef.value.setFields(fields);
        },
        onFinish: () => {
            isLoading.value = false;
        }
    })
}

onMounted(() => {
    refreshCaptcha();
})
</script>

<template>
    <auth-layout>
        <div class="register-section">
            <div class="register-header">
                <h2>创建账户</h2>
                <p>注册新账户，体验智能预约收银系统</p>
            </div>

            <a-form
                ref="FormRef"
                :model="form"
                :rules="rules"
                class="register-form"
                layout="vertical"
                size="large"
                @submit="submitRegister"
            >
                <a-form-item
                    :hide-label="true"
                    field="phone"
                    :label-col-props="{ span: 24 }"
                    :wrapper-col-props="{ span: 24 }"
                    label="手机号"
                >
                    <a-input
                        v-model="form.phone"
                        allow-clear
                        autocomplete="off"
                        class="input-field"
                        placeholder="请输入您的手机号"
                    >
                        <template #prefix>
                            <icon-mobile />
                        </template>
                    </a-input>
                </a-form-item>

                <a-form-item
                    :hide-label="true"
                    :label-col-props="{ span: 24 }"
                    :wrapper-col-props="{ span: 24 }"
                    field="sms_code"
                    label="短信验证码"
                >
                    <div class="sms-code-group">
                        <a-input
                            v-model="form.sms_code"
                            allow-clear
                            autocomplete="off"
                            class="input-field"
                            maxlength="6"
                            placeholder="请输入6位短信验证码"
                        >
                            <template #prefix>
                                <icon-message />
                            </template>
                        </a-input>

                        <a-button
                            :disabled="isSending || countdown > 0"
                            class="sms-button"
                            @click="sendSmsCode"
                        >
                            {{ countdown > 0 ? `${countdown}秒后重发` : (isSending ? '发送中...' : '获取验证码') }}
                        </a-button>
                    </div>
                </a-form-item>

                <a-form-item
                    :hide-label="true"
                    field="password"
                    :label-col-props="{ span: 24 }"
                    :wrapper-col-props="{ span: 24 }"
                    label="密码"
                >
                    <a-input-password
                        v-model="form.password"
                        allow-clear
                        autocomplete="off"
                        class="input-field"
                        placeholder="请设置您的密码"
                    >
                        <template #prefix>
                            <icon-lock />
                        </template>
                    </a-input-password>
                </a-form-item>

                <a-form-item
                    :hide-label="true"
                    field="confirm_password"
                    :label-col-props="{ span: 24 }"
                    :wrapper-col-props="{ span: 24 }"
                    label="确认密码"
                >
                    <a-input-password
                        v-model="form.confirm_password"
                        allow-clear
                        autocomplete="off"
                        class="input-field"
                        placeholder="请再次输入密码"
                    >
                        <template #prefix>
                            <icon-lock />
                        </template>
                    </a-input-password>
                </a-form-item>

                <a-form-item
                    :hide-label="true"
                    field="captcha"
                    label="验证码"
                    :label-col-props="{ span: 24 }"
                    :wrapper-col-props="{ span: 24 }"
                >
                    <div class="captcha-group">
                        <a-input
                            v-model="form.captcha"
                            allow-clear
                            autocomplete="off"
                            class="input-field"
                            placeholder="请输入右侧验证码"
                        >
                            <template #prefix>
                                <icon-safe />
                            </template>
                        </a-input>

                        <div class="captcha-image" title="点击刷新验证码" @click="refreshCaptcha">
                            <img v-if="captchaSrc" :src="captchaSrc" alt="验证码" />
                        </div>
                    </div>
                </a-form-item>

                <a-form-item
                    :hide-label="true"
                    field="agreeToTerms"
                >
                    <a-checkbox v-model="form.agreeToTerms">
                        我已阅读并同意
                        <a-link :hoverable="false" :href="route('terms')" target="_blank">《用户协议》</a-link>
                        和
                        <a-link :hoverable="false" :href="route('privacy')" target="_blank">《隐私政策》</a-link>
                    </a-checkbox>
                </a-form-item>

                <a-form-item :hide-label="true">
                    <a-button
                        :disabled="isLoading"
                        :loading="isLoading"
                        class="register-button"
                        html-type="submit"
                        long
                        size="large"
                        type="primary"
                    >
                        {{ isLoading ? '注册中...' : '立即注册' }}
                    </a-button>
                </a-form-item>
            </a-form>

            <div class="login-link">
                已有账户？ <a-link :hoverable="false" :href="route('login')">立即登录</a-link>
            </div>
        </div>
    </auth-layout>
</template>

<style lang="scss" scoped>
.register-section {
    display: flex;
    flex-direction: column;
    justify-content: center;
    width: 100%;
    max-width: 420px;
    margin: 0 auto;
}

.register-header {
    margin-bottom: 40px;
    text-align: center;
}

.register-header h2 {
    font-size: 28px;
    font-weight: 700;
    color: #1a1a1a;
    margin-bottom: 10px;
}

.register-header p {
    color: #666;
    font-size: 16px;
}

.register-form {
    width: 100%;
}

.input-field {
    border-radius: 10px;
    transition: all 0.3s ease;

    &:focus-within {
        box-shadow: 0 0 0 2px rgba(22, 93, 255, 0.2);
    }
}

.password-tip {
    font-size: 12px;
    color: #999;
    margin-top: 4px;
}

.captcha-group {
    width: 100%;
    display: flex;
    gap: 12px;
    align-items: flex-start;
}

.captcha-image {
    width: 120px;
    height: 34px;
    border-radius: 8px;
    cursor: pointer;
    overflow: hidden;
    flex-shrink: 0;
    position: relative;
    transition: all 0.3s ease;
}

.captcha-image img {
    height: 100%;
    width: auto;
}

.sms-code-group {
    width: 100%;
    display: flex;
    gap: 12px;
    align-items: flex-start;
}

.sms-button {
    width: 120px;
    white-space: nowrap;
    flex-shrink: 0;
    border-radius: 8px;
    height: 34px;
}

.register-button {
    width: 100%;
    padding: 14px;
    background: linear-gradient(135deg, #165DFF, #722ED1);
    color: white;
    border: none;
    border-radius: 10px;
    font-size: 1rem;
    font-weight: 600;
    cursor: pointer;
    transition: all 0.3s ease;
    height: 48px;
    margin-bottom: 20px;
    box-shadow: 0 4px 10px rgba(22, 93, 255, 0.3);

    &:hover:not(:disabled) {
        transform: translateY(-2px);
        box-shadow: 0 6px 15px rgba(22, 93, 255, 0.4);
    }

    &:active {
        transform: translateY(0);
    }
}

.login-link {
    text-align: center;
    margin-top: 20px;
    color: #666;
    font-size: 15px;
}

.login-link a {
    color: #165DFF;
    text-decoration: none;
    font-weight: 500;
}

/* 响应式设计 */
@media (max-width: 576px) {
    .register-section {
        padding: 0 16px;
    }

    .captcha-group {
        flex-direction: column;
    }

    .captcha-image {
        width: 100%;
        height: 45px;
    }

    .register-header h2 {
        font-size: 24px;
    }
}

/* Arco Design 组件样式微调 */
:deep(.arco-form-item-label) {
    font-weight: 500;
    margin-bottom: 8px;
}

:deep(.arco-form-item-extra) {
    margin-top: 4px;
}

:deep(.arco-checkbox-text) {
    font-size: 14px;
}

:deep(.arco-link) {
    font-size: 14px;
}
</style>
